package com.chushouya.manager.dao.repository;

import com.chushouya.manager.dao.entity.OperateLogEntity;
import com.chushouya.manager.dao.mapper.OperateLogEntityMapper;
import com.chushouya.manager.dto.admin.log.OperateLogQueryDTO;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Numbers;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.Objects;

@Repository
@Slf4j
public class OperateLogRepository extends BaseRepository<OperateLogEntityMapper, OperateLogEntity, Long> {

    public void saveOperateLog(OperateLogEntity operateLog) {
        this.insertSelective(operateLog);
    }

    public void clean(Integer cleanBeforeDays) {
        if (!Objects.equals(cleanBeforeDays, Numbers.INTEGER_ZERO)) {
            final Date date = Dates.addDays(new Date(), - cleanBeforeDays);
            final Example example = this.buildExample();
            example.and().andLessThan("time", Dates.getFirstTime(date));
            this.deleteByExample(example);
        } else {
            this.mapper.clean();
        }
    }

    public PageResult<OperateLogEntity> selectPageResult(OperateLogQueryDTO query) {
        final Example example = this.buildExample();
        if(Strings.isNotEmpty(query.getModelName())){
            example.and().andLike("modelName", Strings.format("%{}%", query.getModelName()));
        }
        if(Strings.isNotEmpty(query.getOperateName())){
            example.and().andLike("operateName", Strings.format("%{}%", query.getOperateName()));
        }
        if(Strings.isNotEmpty(query.getUrl())){
            example.and().andLike("url", Strings.format("%{}%", query.getUrl()));
        }
        if(Strings.isNotEmpty(query.getBusinessType())){
            example.and().andEqualTo("businessType", query.getBusinessType());
        }
        if(Strings.isNotEmpty(query.getContextUser())){
            example.and().andLike("contextUser", Strings.format("%{}%", query.getContextUser()));
        }
        if(Objects.nonNull(query.getStatus())){
            example.and().andEqualTo("status", query.getStatus());
        }
        if(Objects.nonNull(query.getBeginTime()) && Objects.nonNull(query.getEndTime())){
            example.and().andGreaterThan("time", query.getBeginTime());
            example.and().andLessThan("time", query.getEndTime());
        }
        example.orderBy("time").desc();
        return this.selectPage(query.getPageRequest(), example);
    }
}
